<template>
  <div class="purchase-application-edit">
    <!-- 顶部操作栏 -->
    <a-card :bordered="false" class="action-buttons-card mb-6">
      <div class="flex justify-between items-center">
        <div class="flex items-center space-x-2">
          <icon-info-circle class="text-blue-600" />
          <span class="text-sm text-gray-600">请填写完整信息后提交</span>
        </div>
        <a-space>
          <a-button type="primary" :loading="submitLoading" @click="onSubmit">
            <template #icon><icon-plus /></template>
            {{ isEdit ? "更新申请" : "提交申请" }}
          </a-button>
          <a-button @click="goBack">
            <template #icon><icon-arrow-left /></template>
            返回
          </a-button>
        </a-space>
      </div>
    </a-card>

    <!-- 表单内容 -->
    <div class="form-content">
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
        size="large"
      >
        <!-- 基础信息 -->
        <a-card title="基础信息" :bordered="false" class="info-card">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item
                field="purchaseApplicationCode"
                label="申请编号"
                required
              >
                <a-input
                  v-model="formData.purchaseApplicationCode"
                  placeholder="请输入申请编号"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                field="purchaseApplicationName"
                label="申请名称"
                required
              >
                <a-input
                  v-model="formData.purchaseApplicationName"
                  placeholder="请输入申请名称"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="applicationTime" label="申请时间" required>
                <a-date-picker
                  v-model="formData.applicationTime"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择申请时间"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <!-- 项目列表 -->
        <a-card :bordered="false" class="project-card">
          <template #title>
            <a-space>
              <span>项目列表</span>
              <a-button type="primary" size="small" @click="addProject">
                <template #icon>
                  <icon-plus />
                </template>
                添加项目
              </a-button>
            </a-space>
          </template>

          <a-space direction="vertical" size="medium" style="width: 100%">
            <div
              v-for="(project, index) in formData.projectItemList"
              :key="index"
              class="project-item"
            >
              <a-card size="small" :bordered="true">
                <template #title>
                  <a-space>
                    <a-tag color="blue">{{ index + 1 }}</a-tag>
                    <span>项目信息</span>
                  </a-space>
                </template>
                <template #extra>
                  <a-button
                    type="text"
                    status="danger"
                    size="mini"
                    @click="removeProject(index)"
                    :disabled="formData.projectItemList.length <= 1"
                  >
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </template>

                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item
                      :field="`projectItemList.${index}.projectName`"
                      label="项目名称"
                      required
                    >
                      <a-input
                        v-model="project.projectName"
                        placeholder="请输入项目名称"
                        allow-clear
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item
                      :field="`projectItemList.${index}.projectCode`"
                      label="项目编号"
                      required
                    >
                      <a-input
                        v-model="project.projectCode"
                        placeholder="请输入项目编号"
                        allow-clear
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item
                      :field="`projectItemList.${index}.projectIndex`"
                      label="项目指标(亩)"
                      required
                    >
                      <a-input
                        v-model="project.projectIndex"
                        placeholder="请输入项目指标(亩)"
                        allow-clear
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-card>
            </div>
          </a-space>
        </a-card>

        <!-- 附件材料 -->
        <a-card title="附件材料" :bordered="false" class="attachment-card">
          <!-- 已有附件展示区域 -->
          <div v-if="existingFiles.length > 0" class="existing-files mb-4">
            <a-typography-text type="secondary">
              <icon-file /> 已上传附件
            </a-typography-text>
            <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
              <a-list-item v-for="file in existingFiles" :key="file.fileId">
                <a-card size="small" hoverable>
                  <a-space>
                    <a-avatar :size="28" shape="square">
                      <icon-file-pdf
                        v-if="file.file?.fileType === 'application/pdf'"
                      />
                      <icon-file-image
                        v-else-if="
                          file.file?.fileType &&
                          ['image/jpeg', 'image/jpg', 'image/png'].includes(
                            file.file.fileType
                          )
                        "
                      />
                      <icon-file v-else />
                    </a-avatar>
                    <div class="file-info">
                      <a-typography-text class="file-name">
                        {{ file.file?.fileName || file.fileName }}
                      </a-typography-text>
                      <div class="file-actions">
                        <a-space size="mini">
                          <a-button
                            size="mini"
                            type="text"
                            @click="downloadFile(file)"
                          >
                            下载
                          </a-button>
                          <a-button
                            size="mini"
                            type="text"
                            @click="previewFile(file)"
                          >
                            预览
                          </a-button>
                          <a-button
                            size="mini"
                            type="text"
                            status="danger"
                            :loading="deleteFileLoading"
                            @click="removeExistingFile(file)"
                          >
                            删除
                          </a-button>
                        </a-space>
                      </div>
                    </div>
                  </a-space>
                </a-card>
              </a-list-item>
            </a-list>
          </div>

          <uploadFile
            ref="attachmentsUploadFileRef"
            :file-source="fs"
            :limit="10"
            :multiple="true"
            accept=".jpg,.png,.jpeg,.pdf,.doc,.docx,.xls,.xlsx"
            list-type="text"
            source-type="proxy"
            @upload-success="handleUploadSuccess"
          />
        </a-card>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import {
  computed,
  defineEmits,
  defineProps,
  getCurrentInstance,
  onMounted,
  onBeforeUnmount,
  reactive,
  ref,
  watch,
} from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconDelete,
  IconPlus,
  IconFile,
  IconFilePdf,
  IconFileImage,
  IconDownload,
  IconEye,
} from "@arco-design/web-vue/es/icon";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import {
  addPurchaseApplicationApi,
  getPurchaseApplicationByPurchaseApplicationIdApi,
  updatePurchaseApplicationByPurchaseApplicationIdApi,
} from "~/api/lindi/purchaseApplication.js";
import { deleteFileApi } from "~/api/basic/file.js";

// 定义props
const props = defineProps({
  purchaseApplicationId: {
    type: String,
    default: "",
  },
});

// 定义事件
const emit = defineEmits(["cancel", "ok"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const deleteFileLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 文件上传引用
const attachmentsUploadFileRef = ref(null);

// 文件来源
const fs =
  fileSource.lindi_purchase_application_attachment?.key ||
  "lindi_purchase_application_attachment";

// 已有附件列表
const existingFiles = ref([]);

// 跟踪新上传的文件ID，用于取消时清理
const newUploadedFileIds = ref([]);

// 是否为编辑模式
const isEdit = computed(() => !!props.purchaseApplicationId);

// 创建新项目对象
const createNewProject = () => ({
  projectId: null,
  projectCode: "",
  projectName: "",
  projectIndex: "",
  purchaseApplicationId: null,
});

// 表单数据
const formData = reactive({
  purchaseApplicationId: null,
  purchaseApplicationCode: "",
  purchaseApplicationName: "",
  purchaseApplicationStatus: "draft",
  applicationTime: null,
  projectItemList: [createNewProject()],
  fileList: [],
  townItemList: [],
});

// 表单规则
const rules = {
  purchaseApplicationCode: [
    { required: true, message: "申请编号不能为空" },
    { min: 1, max: 50, message: "申请编号长度为1-50个字符" },
  ],
  purchaseApplicationName: [
    { required: true, message: "申请名称不能为空" },
    { min: 1, max: 100, message: "申请名称长度为1-100个字符" },
  ],
  applicationTime: [{ required: true, message: "申请时间不能为空" }],
  // 动态生成项目规则
  ...generateProjectRules(),
};

// 生成项目验证规则
function generateProjectRules() {
  const projectRules = {};
  if (formData.projectItemList && Array.isArray(formData.projectItemList)) {
    formData.projectItemList.forEach((_, index) => {
      projectRules[`projectItemList.${index}.projectCode`] = [
        { required: true, message: "请输入项目编号", trigger: "blur" },
      ];
      projectRules[`projectItemList.${index}.projectName`] = [
        { required: true, message: "请输入项目名称", trigger: "blur" },
      ];
      projectRules[`projectItemList.${index}.projectIndex`] = [
        { required: true, message: "请输入项目指标", trigger: "blur" },
      ];
    });
  }
  return projectRules;
}

// 添加项目
const addProject = () => {
  formData.projectItemList.push(createNewProject());
  // 重新生成验证规则
  Object.assign(rules, generateProjectRules());
};

// 删除项目
const removeProject = (index) => {
  if (formData.projectItemList.length <= 1) {
    Message.warning("至少需要保留一个项目");
    return;
  }
  formData.projectItemList.splice(index, 1);
  // 重新生成验证规则
  Object.assign(rules, generateProjectRules());
};

// 附件上传成功处理
const handleUploadSuccess = (response) => {
  console.log("附件上传成功:", response);
  if (response && response.fileId) {
    // 将上传的文件添加到formData.fileList中
    const newFile = {
      fileId: response.fileId,
      purchaseApplicationId: formData.purchaseApplicationId,
    };

    // 如果formData.fileList不存在，初始化为空数组
    if (!formData.fileList) {
      formData.fileList = [];
    }

    // 添加新文件到列表中
    formData.fileList.push(newFile);

    if (!isEdit.value) {
      newUploadedFileIds.value.push(response.fileId);
    }
    proxy.$msg.success("附件上传成功");
  }
};

// 下载文件
const downloadFile = (file) => {
  const fileUrl = file.file?.fileUrl || file.fileUrl;
  if (fileUrl) {
    window.open(fileUrl, "_blank");
  } else {
    proxy.$msg.error("文件下载链接不存在");
  }
};

// 预览文件
const previewFile = (file) => {
  const fileUrl = file.file?.fileUrl || file.fileUrl;
  if (fileUrl) {
    window.open(fileUrl, "_blank");
  } else {
    proxy.$msg.error("文件预览链接不存在");
  }
};

// 删除已有附件
const removeExistingFile = (file) => {
  const fileName = file.file?.fileName || file.fileName;
  proxy.$modal.confirm({
    title: "确认删除",
    content: `确定要删除附件 "${fileName}" 吗？`,
    onOk: () => {
      deleteFileLoading.value = true;

      // 模拟删除API调用
      setTimeout(() => {
        // 从已有附件列表中移除
        existingFiles.value = existingFiles.value.filter(
          (item) => item.fileId !== file.fileId
        );

        // 从formData.fileList中移除
        if (formData.fileList && Array.isArray(formData.fileList)) {
          formData.fileList = formData.fileList.filter(
            (item) => item.fileId !== file.fileId
          );
        }

        // 从上传组件的文件列表中移除
        if (
          attachmentsUploadFileRef.value &&
          attachmentsUploadFileRef.value.fileList
        ) {
          attachmentsUploadFileRef.value.fileList =
            attachmentsUploadFileRef.value.fileList.filter(
              (item) => item.uid !== file.fileId
            );
        }

        hasFormChanged.value = true;
        proxy.$msg.success("附件删除成功");
        deleteFileLoading.value = false;
      }, 500);
    },
  });
};

// 检查表单是否有变更
const hasFormChanged = ref(false);

// 返回列表页
const goBack = () => {
  if (hasFormChanged.value) {
    proxy.$modal.confirm({
      title: "确认离开",
      content: "您有未保存的更改，确定要离开吗？",
      onOk: async () => {
        await cleanupUnusedFiles();
        emit("cancel");
      },
    });
  } else {
    emit("cancel");
  }
};

// 清理未使用的文件
const cleanupUnusedFiles = async () => {
  for (const fileId of newUploadedFileIds.value) {
    try {
      await deleteFileApi(fileId);
    } catch (error) {
      console.error("删除文件失败:", error);
    }
  }
  newUploadedFileIds.value = [];
};

// 获取购买申请详情
const getPurchaseApplicationDetail = () => {
  if (!props.purchaseApplicationId) return Promise.resolve();

  loading.value = true;
  return getPurchaseApplicationByPurchaseApplicationIdApi(
    props.purchaseApplicationId
  )
    .then((response) => {
      const data = response;

      // 直接使用formData=response方式，忽略审计字段
      Object.assign(formData, {
        purchaseApplicationId: data.purchaseApplicationId,
        purchaseApplicationCode: data.purchaseApplicationCode || "",
        purchaseApplicationName: data.purchaseApplicationName || "",
        purchaseApplicationStatus: data.purchaseApplicationStatus || "draft",
        applicationTime: data.applicationTime || null,
        projectItemList:
          data.projectItemList && data.projectItemList.length > 0
            ? data.projectItemList
            : [createNewProject()],
        fileList: data.fileList || [],
        townItemList: data.townItemList || [],
      });

      // 设置已有附件列表
      existingFiles.value = data.fileList || [];
    })
    .catch((error) => {
      console.error("获取购买申请详情失败:", error);
      Message.error("获取详情失败: " + (error.message || "网络错误"));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 提交表单
const submitForm = () => {
  formRef.value
    .validate()
    .then((valid) => {
      if (!valid) {
        submitLoading.value = true;

        // 构建提交数据
        const submitData = {
          purchaseApplicationCode: formData.purchaseApplicationCode,
          purchaseApplicationName: formData.purchaseApplicationName,
          purchaseApplicationStatus: formData.purchaseApplicationStatus,
          applicationTime: formData.applicationTime,
          projectItemList: formData.projectItemList.map((project) => ({
            projectId: project.projectId,
            projectCode: project.projectCode,
            projectName: project.projectName,
            projectIndex: project.projectIndex,
            purchaseApplicationId: formData.purchaseApplicationId,
          })),
          fileList: (formData.fileList || []).map((file) => ({
            fileId: file.fileId,
            purchaseApplicationId: formData.purchaseApplicationId,
          })),
          townItemList: formData.townItemList || [],
        };

        // 如果是编辑模式，添加ID
        if (props.purchaseApplicationId) {
          submitData.purchaseApplicationId = props.purchaseApplicationId;
        }

        console.log("提交数据:", submitData);

        const apiCall = props.purchaseApplicationId
          ? updatePurchaseApplicationByPurchaseApplicationIdApi(submitData)
          : addPurchaseApplicationApi(submitData);

        apiCall
          .then((response) => {
            if (response && response.code === 200) {
              Message.success(
                props.purchaseApplicationId ? "修改成功" : "新增成功"
              );
              newUploadedFileIds.value = []; // 清理文件ID列表
              emit("ok");
            } else {
              Message.error(response?.message || "操作失败");
            }
          })
          .catch((error) => {
            console.error("提交失败:", error);
            Message.error("提交失败: " + (error.message || "网络错误"));
          })
          .finally(() => {
            submitLoading.value = false;
          });
      }
    })
    .catch((error) => {
      console.error("表单验证失败:", error);
    });
};

// 组件挂载时执行
onMounted(() => {
  if (isEdit.value) {
    getPurchaseApplicationDetail();
  }
});

// 组件卸载时清理
onBeforeUnmount(async () => {
  // 如果有未保存的文件，清理它们
  if (newUploadedFileIds.value.length > 0) {
    await cleanupUnusedFiles();
  }
});
</script>

<style scoped>
.purchase-application-edit {
  min-height: 100vh;
  background-color: var(--color-fill-1);
}

.action-bar {
  padding: 12px 24px;
  background: var(--color-bg-1);
  border-bottom: 1px solid var(--color-border-2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 16px;
}

.project-card {
  margin-bottom: 16px;
}

.project-item {
  width: 100%;
}

.attachment-card {
  margin-top: 16px;
}

.existing-files {
  margin-bottom: 16px;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  display: block;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-actions {
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-content {
    padding: 16px;
  }

  .action-bar {
    padding: 8px 16px;
  }
}

/* 表单项间距优化 */
:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-card-body) {
  padding: 16px;
}

:deep(.arco-card-header) {
  padding: 12px 16px;
  border-bottom: 1px solid var(--color-border-2);
}
</style>
